package bblvolume

type Job struct {
	Id   int
	Name string
	Args map[string]string
}

var (
	op_job = map[string]HandlerJob{
		"MOVE":     do_move_job,
		"DOWN":     do_down_job,
		"DELETE":   do_delete_job,
		"COPY":     do_copy_job,
		"TRUNCATE": do_truncate_job,
	}
)

type HandlerJob func(fs StorageSystem, job *Job)

type WorkerServer struct {
	signals chan bool
	fs      StorageSystem
}

func NewWorkerServer(fs StorageSystem) (*WorkerServer, error) {
	return &WorkerServer{signals: make(chan bool), fs: fs}, nil
}

func (w *WorkerServer) Serve() {
	for {
		select {
		case <-w.signals:
			return
		default:
			vstat := VolumeStat()
			vstat.StoreStat = w.fs.StorageStat()
			jobs, err := GetJob("http://"+w.fs.ClusterServer()[0]+"/"+w.fs.UUID(), vstat)
			if err != nil {
				log.Error(err)
				Sleep(5000)
				continue
			}
			if jobs != nil && len(jobs) > 0 {
				for _, job := range jobs {
					w.do_job(&job)
				}
			} else {
				Sleep(5000)
			}
		}

	}
}

func (w *WorkerServer) Stop() {
	w.signals <- true
}

func (w *WorkerServer) do_job(job *Job) {
	defer func() {
		if e := recover(); e != nil {
			log.Error(e)
		}
	}()
	if handler, exist := op_job[job.Name]; exist {
		handler(w.fs, job)
	} else {
		log.Error("job", job.Name, "no handler")
	}
}

func do_move_job(fs StorageSystem, job *Job) {

}

func do_down_job(fs StorageSystem, job *Job) {

}

func do_delete_job(fs StorageSystem, job *Job) {

}

func do_copy_job(fs StorageSystem, job *Job) {

}

func do_truncate_job(fs StorageSystem, job *Job) {

}
